#!/usr/bin/env python

import XenAPI
import XenAPIPlugin
import sys
import urllib2
import base64
from xml.dom.minidom import parse

path 	= "/opt/tpm/"
tpmcert     = path + "tpm.cert"
xmlfile     = path + "xenaik.xml"
aiktcpa     = path + "aik_tcpa.pub"
ekpub      = path +  "ek_pem.pub"
aikpub      = path + "aik_pem.pub"

tempxml = "/tmp/out.xml"

error_strings =  { tpmcert:   'Error in Reading TPM certificate',\
                  'unknown': 'Error happend in AIK request ',\
                   xmlfile:  'Error in XML Schema file',\
                   aiktcpa:  'Error in Reading AIK TCPA Pub Key',\
                   aikpub:   'Error in Reading XenServer Public Key',\
                   ekpub:   'Error in Reading AIK Public Key' }

error   = 'unknown'
##Create an XML with
## certifciate, public keys
def gen_out_xml():
    global error
    try:
        dom = parse(xmlfile)
        root = dom.getElementsByTagName("xentxt:xentxtdata")
        tpmcert_node = dom.getElementsByTagName('xentxt:TPM_Endorsement_Certficate')[0]
        ekpub_node  = dom.getElementsByTagName("xentxt:TPM_Endorsement_KEY_PEM")[0]
        aikpub_node  = dom.getElementsByTagName("xentxt:TPM_Attestation_KEY_PEM")[0]
        aiktcp_node  = dom.getElementsByTagName("xentxt:TPM_Attestation_KEY_TCPA")[0]
    except:
        error = xmlfile
	raise
    self = True
    try:
	f = open (tpmcert)
        tpmcert_node.firstChild.nodeValue = base64.b64encode(f.read())
        f.close()
        self = False;
    except:
        tpmcert_node.firstChild.nodeValue = ''
    try:
        f = open(ekpub)
        ekpub_node.firstChild.nodeValue =  base64.b64encode(f.read())
        f.close()
    except:
        error = ekpub
	raise
    try:
        f = open(aiktcpa)
        aiktcp_node.firstChild.nodeValue = base64.b64encode(f.read())
        f.close()
    except:
        error = aiktcpa
	raise
    try:
        f = open(aikpub)
        aikpub_node.firstChild.nodeValue = base64.b64encode(f.read())
        f.close()
    except:
        error = aikpub
   	raise
    f = open(tempxml,"w");
    f.write(dom.toxml())
    f.close()

def main(session, args):
    try:
        gen_out_xml()
        f = open(tempxml,"r")
        data = f.read()
        return data
    except:
        try:
	    return error_strings[error]
        except:
            return "Error While getting AIK data"

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"main":main})
    #print main(None,None)
